import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.await
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.w3c.dom.CustomEvent
import org.w3c.dom.CustomEventInit
import org.w3c.dom.Element
import org.w3c.dom.HTMLButtonElement
import org.w3c.dom.events.Event
import org.w3c.dom.get
import util.isLoginPage

external val chrome: dynamic

fun main() {
  println("hello world")
  addEvents()
}

fun addEvents() {
  window.addEventListener("hashchange", ::handler)
  window.addEventListener("load", ::handler)
}

fun handler(event: Event) {
  println("hashchange or load")
  if (!isLoginPage()) {
    return
  }
  CoroutineScope(Dispatchers.Default).launch {
    if (!checkInput()) {
      return@launch
    }
    fillInputData()
    fetchData()
  }
}

suspend fun checkInput(): Boolean {
  var count = 10;
  while (count-- > 0) {
    println("checking")
    if (document.querySelector("input[placeholder=\"请输入用户名\"]") != null) {
      return true
    }
    delay(1000)
  }
  return false
}

fun dispatchInputEvent(dom: Element, value: String) = dom.also {
  it.asDynamic().value = value
  it.dispatchEvent(CustomEvent("input", CustomEventInit(bubbles = true)))
}

fun fillInputData() {
  document.querySelectorAll(".el-tabs__item")[1]?.asDynamic()?.click()
  document.querySelector(".el-input__inner[placeholder='请输入用户名']")?.also {
    dispatchInputEvent(it, "mazheng")
  }
  document.querySelector(".el-input__inner[placeholder='请输入密码']")?.also {
    dispatchInputEvent(it, "123456")
  }

  document.createElement("button").also {
    when (it) {
      is HTMLButtonElement -> {
        it.style.cssText += "position: absolute; top: 0;"
        it.textContent = "Click Me"
        it.addEventListener("click", {
          chrome.runtime.sendMessage("hello")
        })
      }
    }
    document.body?.append(it)
  }
}

suspend fun fetchData() {
//  window.fetch("https://www.baidu.com").await().text().await().also {
//    println(it)
//  }
}
